package algorithm7.leetcode.链表;

public class LC21_2 {

/*
21. 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

输入：l1 = [1,2,4], l2 = [1,3,4]
输出：[1,1,2,3,4,4]
*/

    //     * Definition for singly-linked list.
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class Solution {

        public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
            if (list1 == null || list2 == null) return list1 == null ? list2 : list1;
            ListNode head;
            ListNode cur1;
            ListNode cur2;
            if (list1.val < list2.val) {
                head = list1;
                cur1 = list1.next;
                cur2 = list2;
            } else {
                head = list2;
                cur1 = list1;
                cur2 = list2.next;
            }
            ListNode cur = head;
            while (cur1 != null && cur2 != null) {
                if (cur1.val < cur2.val) {
                    cur.next = cur1;
                    cur = cur1;
                    cur1 = cur1.next;
                } else {
                    cur.next = cur2;
                    cur = cur2;
                    cur2 = cur2.next;
                }
            }
            if (cur1 != null) {
                cur.next = cur1;
            } else {
                cur.next = cur2;
            }
            return head;
        }

    }

    public static void main(String[] args) {
        ListNode l1 = new LC21_2().new ListNode(1);
        ListNode l2 = new LC21_2().new ListNode(2);
        l1.next = new LC21_2().new ListNode(4);
        l1.next.next = new LC21_2().new ListNode(5);
        l2.next = new LC21_2().new ListNode(3);
        l2.next.next = new LC21_2().new ListNode(6);
        l2.next.next.next = new LC21_2().new ListNode(9);
        l2.next.next.next.next = new LC21_2().new ListNode(15);
        ListNode head = new LC21_2().new Solution().mergeTwoLists(l1, l2);
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
    }

}
